<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://static.talkyun.com/frame/layui/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="https://static.talkyun.com/frame/layui/style/skin/default.css" media="all">
    <link rel="stylesheet" href="../css/style.css" media="all">
    <script src="../js/jquery.min.js"></script>
    <script src="../js/common.js"></script>
    <script src="../layui/layui.js"></script>
    <script src="../js/api.js"></script>
    <script src="index.js"></script>
</head>

<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>内容管理</legend>
</fieldset>

<table class="layui-hide" id="test" lay-filter="testevent"></table>

<!--    模板scripty-->
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="addItem">添加内容</button>
    </div>
</script>

<!--    弹出窗的模板-->
<script type="text/html" id="argSchemaTemplate">
    <form class="layui-form" action="">
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
            <legend>发布文章</legend>
        </fieldset>

        <div class="layui-input-block" hidden>
            <input class="layui-input" type="text" hidden name="id" value="{{d.id}}" autocomplete="off"
                   placeholder="请输入id"/>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">文章标题</label>
            <div class="layui-input-block">
                <input class="layui-input" type="text" lay-verify="required" name="contentname"
                       value="{{d.contentname}}" autocomplete="off" placeholder="请输入标题"/>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">文章描述</label>
            <div class="layui-input-block">
                <input class="layui-input" type="text" lay-verify="required" name="contentdescription"
                       value="{{d.contentdescription}}" autocomplete="off" placeholder="请输入描述"/>

            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">tag标签</label>
            <div class="layui-input-block">
                <input class="layui-input" type="text" lay-verify="required" name="tag" value="{{d.tag}}"
                       autocomplete="off" placeholder="请输入标签"/>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">作者</label>
            <div class="layui-input-block">
                <input class="layui-input" type="text" lay-verify="required" name="author" value="{{d.author}}"
                       autocomplete="off" placeholder="请输入作者"/>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">分类目录</label>
            <div class="layui-input-block">
                <select name="categoryname" lay-filter="categoryname" id="categoryname">
                    
                </select>
            </div>
        </div> 


        <div class="layui-form-item">
            <label class="layui-form-label">中小学</label>
            <div class="layui-input-block">
                <select name="parentgrade" lay-filter="parentgrade" id="parentgrade">
                   
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">年级</label>
            <div class="layui-input-block">
                <select name="grade" lay-filter="grade" id="grade">
                    
                </select>
            </div>
        </div>

        <div class="layui-upload">
            <label class="layui-form-label"></label>
            <button type="button" class="layui-btn" id="uploadId">上传图片</button>
            <div class="layui-upload-list">
                <img class="layui-upload-img" id="uploadImgId" src="{{d.picurl}}">
                <p id="demoText"></p>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">是否推荐</label>
            <div class="layui-input-block">
                <input type="radio" name="isrecommend" id="radio_true" value="是" title="是">
                <input type="radio" name="isrecommend" id="radio_false" value="否" title="否">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">权重</label>
            <div class="layui-input-block">
                <input class="layui-input" type="text" name="weight" value="{{d.weight}}" autocomplete="off"
                       placeholder="请输入权重"/>
            </div>
        </div>

        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">内容</label>
            <div class="layui-input-block">
                <textarea id="areatext" name="areatext" style="width:700px;height:300px;">
                        {{d.areatext}}
                    </textarea>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label"> 图片链接</label>
            <div class="layui-input-block">
                <input class="layui-input" type="text" id="picUrl" name="picurl" value="{{d.picurl}}"
                       autocomplete="off"/>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label"></label>
            <button type="submit" class="layui-btn" lay-submit="" lay-filter="submitadvertmanager">提交</button>
        </div>
    </form>

</script>
<script type="text/html" id="PicurlTpl">
    <img class="layui-upload-img" id="uploadImgId21" src="{{d.picurl}}">
</script>

</body>
<script charset="utf-8" src="/static/boss/kindeditor/kindeditor-all-min.js"></script>
<script charset="utf-8" src="/static/boss/kindeditor/lang/zh-CN.js"></script>
<!--<script charset="utf-8" src="/kindeditor/kindeditor-all.js"></script>-->
<!--<script charset="utf-8" src="/kindeditor/lang/zh-CN.js"></script>-->
<script>
    KindEditor.ready(function (K) {
        window.editor = K.create('#areatext', {
            uploadJson: 'https://bckapp.qiwenedu.com.cn/advert/image/layedit',
            afterUpload: function () {
                this.sync();
            },
            allowFileManager: true
        });
    });
</script>
<script type="text/javascript">
    layuiModules = ['table', 'form', 'laydate', 'admin', 'upload', 'layedit'];

    function mounted() {
//
        var form = layui.form,
            layer = layui.layer,
            laydate = layui.laydate;
        var table = layui.table;
        var $ = layui.$;
        var api = layui.api;
        var admin = layui.admin;
        var upload = layui.upload;
//            var layedit = layui.layedit;
        var where = {};

        table.render({
            elem: '#test',
            url: api.contentmanager.allAdmin,
            cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            toolbar: '#toolbarDemo', //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
            defaultToolbar: {},
            page: true,
            request: {
                pageName: "pageNo",
                limitName: "pageSize"
            },
            contentType: "application/json",
            parseData: function (res) {
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.data.totalSize,
                    "data": res.data.result
                }
            },
            done: function (res, curr, count) {
//                    loadPage(curr, count);
            },
            cols: [
                [{
                    type: 'checkbox',
                    fixed: 'left'
                }, {
                    field: 'id',
                    width: 120,
                    title: 'ID'
                }, {
                    field: 'contentname',
                    width: 120,
                    title: '文章标题'
                }, {
                    field: 'contentdescription',
                    width: 120,
                    title: '文章描述'
                }, {
                    field: 'tag',
                    width: 120,
                    title: 'tag标签'
                }, {
                    field: 'categoryname',
                    width: 120,
                    title: '分类目录'
                }, {
                    field: 'picurl',
                    title: '图片预览',
                    width: 120,
                    templet: '#PicurlTpl'
                }, {
                    field: 'isrecommend',
                    width: 120,
                    title: '推荐'
                }, {
                    field: 'weight',
                    title: '权重',
                    width: 120
                }, {
                    field: 'createTime',
                    width: 120,
                    title: '日期'
                }, {
                    field: 'author',
                    title: '作者',
                    width: 120
                }, {
                    fixed: 'right',
                    width: 165,
                    align: 'center',
                    toolbar: '#barDemo'
                }]
            ],
            where: where
        });

        form.render();

        var map = {
            '小学': ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级'],
            '初中': ['初一', '初二', '初三'],
            '高中': ['高一', '高二', '高三']
        }
        layui.use('form', function () {
            form.on('select(parentgrade)', function (data) {
                if (!data) return
                if (!map[data.value]) return
                let arr = map[data.value]
                $("#grade").empty();
                $('#grade').append(new Option('', ''))
                arr.forEach(label => {
                    $('#grade').append(new Option(label, label))
                });
                layui.form.render("select");//重新渲染 固定写法
            });
        });

        //监听提交
        form.on('submit(submitadvertmanager)', function (data) {
            if (data.field.id && data.field.id != 'undefined' && data.field.id != '') {
                data.field.areatext = window.editor.html();
                data.field.categoryname =  $("#categoryname").find("option:selected").text();
                data.field.parentgrade =  $("#parentgrade").find("option:selected").text();
                data.field.grade =  $("#grade").find("option:selected").text();
                updateItem(data);
            } else {
                data.field.areatext = window.editor.html();
                data.field.categoryname =  $("#categoryname").find("option:selected").text();
                data.field.parentgrade =  $("#parentgrade").find("option:selected").text();
                data.field.grade =  $("#grade").find("option:selected").text();
                addItem(data);
            }
            return false;
        });

        //监听头工具栏事件
        table.on('toolbar(testevent)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id),
                data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'addItem':
                    openlayer({
                        areatext: "",
                        author: "",
                        categoryname: "",
                        contentdescription: "",
                        contentname: "",
                        grade: "",
                        parentgrade: "",
                        picurl: "",
                        tag: "",
                        weight: ""
                    });
                    break;
            }
            ;
        });

        //监听行工具事件
        table.on('tool(testevent)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                ,
                layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'detail') {
                layer.msg('查看操作');
            } else if (layEvent === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构
                    layer.close(index);
                    //向服务端发送删除指令
                    admin.req({
                        url: `${api.contentmanager.delete}?id=${obj.data.id}`,
                        contentType: 'application/x-www-form-urlencoded',
                        async: false,
                        success: function (res) {
                            layer.msg('删除成功');
                        }
                    });
                });
            } else if (layEvent === 'edit') {
                console.log({data})
                layer.msg('编辑操作');
                // var tga01 = data.categoryname
                // $('#categoryname').siblings("div.layui-form-select").find('dl').find(tga01).click();
                openlayer(data);
            }
        });

        //新增和编辑同一个  试一试
        function addItem(data) {
            data.field.isrecommend = data.field.isrecommend == "是" ? 1 : 0;
            console.log("addItem====" + data)
            admin.req({
                url: api.contentmanager.add,
                data: data.field,
                async: false,
                success: function (res) {
                    layer.msg('新增成功');
                    layer.closeAll();
                    table.reload('test', {where: where});
                }
            });
        }

        function updateItem(data) {
            data.field.isrecommend = data.field.isrecommend == "是" ? 1 : 0;
            console.log("updateItem====" + data)
            admin.req({
                url: api.contentmanager.update,
                data: data.field,
                async: false,
                success: function (res) {
                    layer.msg('修改成功');
                    layer.closeAll();
                    table.reload('test', {where: where});
                }
            });
        }

        function openlayer(data) {
            var templet = $('#argSchemaTemplate').html();

            layui.laytpl(templet).render(data, function (html) {
                //layer 弹出窗
                //在这里面输入任何合法的js语句

                layer.open({
                    type: 1 //Page层类型
                    ,
                    area: ['70%', '80%'],
                    title: '',
                    maxmin: false //允许全屏最小化
                    ,
                    anim: -1 //0-6的动画形式，-1不开启
                    ,
                    content: html,
                    success: function (layero, index) {
                        if (data.isrecommend === 1) { //判断是否选中
                            $('#radio_true').prop("checked", true);
                            $('#radio_false').prop("checked", false);
                        } else {
                            $('#radio_true').prop("checked", false);
                            $('#radio_false').prop("checked", true);
                        }
                        layedit.set({ //设置图片接口
                            uploadImage: {
                                url: api.advertDetail.uploadLayedit, //接口url
                                type: 'post',
                            }
                        });
                        KindEditor.ready(function (K) {
                            window.editor = K.create('#areatext', {
                                uploadJson: 'https://bckapp.qiwenedu.com.cn/advert/image/layedit',
                                afterUpload: function () {
                                    this.sync();
                                },
                                allowFileManager: true
                            });
                        });
                        loadCategoryData(0);
                        //普通图片上传
                        var uploadInst = upload.render({
                            elem: '#uploadId',
                            url: api.advertDetail.upload //改成您自己的上传接口
                            ,
                            before: function (obj) {
                                //预读本地文件示例，不支持ie8
                                obj.preview(function (index, file, result) {
                                    $('#uploadImgId').attr('src', result); //图片链接（base64）
                                });
                            },
                            done: function (res) {
                                //如果上传失败
                                if (res.code > 0) {
                                    return layer.msg('上传失败');
                                }
                                //上传成功
                                $('#picUrl').val(res.data);

                            },
                            error: function () {
                                //演示失败状态，并实现重传
                                var demoText = $('#demoText');
                                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                                demoText.find('.demo-reload').on('click', function () {
                                    uploadInst.upload();
                                });
                            }
                        });
                        form.render();
                    }
                });
            });
        }

        function loadCategoryData(parentId) {
            admin.req({
                url: api.category.queryByParentId + parentId,
                async: false,
                success: function (res) {
                    if (res.data != null) {
                        var $html = '<option value="">请选择</option>';
                        $.each(res.data, function (index, item) {
                            $html += "<option value='" + item.id + "'>" + item.name + "</option>";
                        });
                        $("#categoryname").append($html);
                        //append后必须从新渲染
                        form.render('select');
                    }
                }
            });
        }

        //监听省下拉框
        form.on('select(categoryname)', function(dataObj){
            //移除城市下拉框所有选项
            $("#parentgrade").empty();
            var parentgradeHtml = '<option value="">请选择</option>';
            $("#parentgrade").html(parentgradeHtml);
            var gradeHtml = '<option value="">请选择</option>';
            $("#grade").html(gradeHtml);
            var parentId = $("#categoryname").find("option:selected").val();
            //异步加载下拉框数据
            admin.req({
                url: api.category.queryByParentId + parentId,
                async: false,
                success: function (res) {
                    if (res.data != null) {
                        $("#parentgrade").empty();
                        var $html = '<option value="">请选择</option>';
                        $.each(res.data, function (index, item) {
                            $html += "<option value='" + item.id + "'>" + item.name + "</option>";
                        });
                        $("#parentgrade").append($html);
                        //append后必须从新渲染
                        form.render('select');
                    }
                }
            });

        });

        //监听市下拉框
        form.on('select(parentgrade)', function(dataObj){
            //移除县区下拉框所有选项
            $("#grade").empty();
            var html = '<option value="">请选择</option>';
            $("#grade").html(html);

            var parentId = $("#parentgrade").find("option:selected").val();
            //异步加载下拉框数据
            //异步加载下拉框数据
            admin.req({
                url: api.category.queryByParentId + parentId,
                async: false,
                success: function (res) {
                    if (res.data != null) {
                        $("#grade").empty();
                        var $html = '<option value="">请选择</option>';
                        $.each(res.data, function (index, item) {
                            $html += "<option value='" + item.id + "'>" + item.name + "</option>";
                        });
                        $("#grade").append($html);
                        //append后必须从新渲染
                        form.render('select');
                    }
                }
            });
        });
    };
</script>
</html>